package com.js.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.js.admin.entity.BaseDepart;
import com.js.admin.entity.BaseUser;
import com.js.admin.mapper.BaseDepartMapper;
import com.js.admin.mapper.BaseUserMapper;
import com.js.admin.service.BaseDepartService;
import com.js.common.exception.base.BusinessException;
import com.js.common.response.TableResultResponse;
import com.js.common.service.impl.BizServiceImpl;
import com.js.common.util.SnowFlakeUtil;
import com.js.core.context.BaseContextHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author： ygl
 * @date： 2018/3/26
 * @Description：
 */
@Service
public class BaseDepartServiceImpl extends BizServiceImpl<BaseDepart> implements BaseDepartService {

    @Autowired
    private BaseDepartMapper baseDepartMapper;

    @Autowired
    private BaseUserMapper baseUserMapper;

    @Override
    public TableResultResponse<BaseUser> getDepartUsers(String departId, String userName) {
        List<BaseUser> users = baseDepartMapper.selectDepartUsers(departId, userName);
        return new TableResultResponse<BaseUser>(users.size(), users);
    }

    @Override
    public void addDepartUser(String departId, String userIds) {
        if (!StringUtils.isEmpty(userIds)) {
            String[] uIds = userIds.split(",");
            for (String uId : uIds) {
                String userId = SnowFlakeUtil.getFlowIdInstance().nextId() + "";
                baseDepartMapper.insertDepartUser(userId, departId, uId, BaseContextHandler.getTenantId());
            }
        }
    }

    @Override
    public void delDepartUser(String departId, String userId) {
        BaseUser user = baseUserMapper.selectByPrimaryKey(userId);
        if (user.getDepartId().equals(departId)) {
            throw new BusinessException("无法移除用户的默认关联部门,若需移除,请前往用户模块更新用户部门!");
        }
        baseDepartMapper.deleteDepartUser(departId, userId);
    }

    @Override
    public Map<String, String> getDeparts(String departIds) {
        if (StringUtils.isBlank(departIds)) {
            return new HashMap<>();
        }
        departIds = "'" + departIds.replaceAll(",", "','") + "'";
        List<BaseDepart> departs = baseDepartMapper.selectByIds(departIds);
        return departs.stream().collect(Collectors.toMap(BaseDepart::getId, depart -> JSONObject.toJSONString(depart)));
    }
}
